using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 工单排程命令。
/// </summary>
public sealed record ScheduleWorkOrderCommand(long WoId) : IRequest<IResult<bool>>;

internal sealed class ScheduleWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<ScheduleWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(ScheduleWorkOrderCommand request, CancellationToken cancellationToken)
    {
        var workOrder = await repo.GetByIdAsync(request.WoId, cancellationToken);
        if (workOrder == null)
        {
            return Result.Failure("未找指定的工单");
        }

        if (workOrder.Status is not WoStatusEnum.Issued)
        {
            return Result.Failure("工单不处于下发状态，不能排产"); // 目前没有审批流程
        }

        // 按产线分组，找到产线中最大的优先级值。
        var max = await repo.MaxAsync(m => m.LineId == workOrder.LineId, m => m.Priority, cancellationToken);

        workOrder.ChangeStatus(WoStatusEnum.Scheduled);
        workOrder.Priority = max + 1;
        var ok = await repo.UpdateAsync(workOrder, m => new
        {
            m.Priority,
            m.LastStatus,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
